//
//  MCStoreDetailViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/26.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCStoreDetailViewController: MCViewController {

    
    private var storeDict : [String : Any] = [:]
    private var refundAddress : [String : Any] = [:]

    
    private var firstStoreBgimage : String = ""
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sendNetworking()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        managerClosure()
    }

    // MARK: - Setter & Getter
    lazy var topView: MCStoreDetailTopView = {
        let view = MCStoreDetailTopView()
        view.drawMoneyButton.addTarget(self, action: #selector(drawMoneyButtonClicked), for: UIControlEvents.touchUpInside)
        return view
    }()
    
    
    lazy var deliveryView: MCStoreDetailItemView = {
        let view = MCStoreDetailItemView()
        view.titleLabel.text = "配送方式"
        view.detailLabel.text = ""
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(deliveryViewEvent))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var returnInfoView: MCStoreDetailItemView = {
        let view = MCStoreDetailItemView()
        view.titleLabel.text = "退货信息"
        view.detailLabel.text = ""
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(returnInfoViewEvent))
        view.addGestureRecognizer(tap)

        return view
    }()
    
    lazy var storeBgImageView: MCStoreDetailItemView = {
        let view = MCStoreDetailItemView()
        view.titleLabel.text = "修改店铺背景图"
        view.detailLabel.text = ""
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(storeBgImageViewEvent))
        view.addGestureRecognizer(tap)
        
        return view
    }()
    
//    lazy var paymentCodeView: MCStoreDetailItemView = {
//        let view = MCStoreDetailItemView()
//        view.titleLabel.text = "店铺收款码"
//        view.detailLabel.text = ""
//        let tap = UITapGestureRecognizer.init(target: self, action: #selector(paymentCodeViewEvent))
//        view.addGestureRecognizer(tap)
//        return view
//    }()
    
    lazy var changeStoreView: MCStoreDetailItemView = {
        let view = MCStoreDetailItemView()
        view.titleLabel.text = "切换店铺"
        view.detailLabel.text = ""
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(changeStoreViewEvent))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var chooseImageView: MCChooseImageView = {
        let view = MCChooseImageView()
        view.isNeedEditImage = false
        view.superViewController = self
        

        return view
    }()
}


extension MCStoreDetailViewController:SwiftyPhotoClipperDelegate {
    //选择图片成功后代理
    

    
    func didFinishClippingPhoto(image: UIImage) {
        // 上传图片
        self.sendNewworking_updateImage(image)
    }
    
}


//MARK: 通知回调，闭包回调，点击事件
extension MCStoreDetailViewController {
    
    @objc func managerClosure() {
        chooseImageView.closure = { image
            in
            
            // 进入图片裁切图片
            let clipper = SwiftyPhotoClipper()
            clipper.delegate = self
            clipper.img = image
            self.present(clipper, animated: true, completion: nil)
        }
    }

    
    
    @objc func rightItemClicked() {
        let vc = MCShareStoreViewController()
        vc.storeName = storeDict["storeName"] as? String ?? ""
        vc.storeId = storeDict["storeId"] as? Int ?? 0
        vc.storeIconImageStr = storeDict["logoPath"] as? String ?? ""        
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func drawMoneyButtonClicked() {
        let vc = MCWithdrawMoneyViewController()
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    //    @objc func paymentCodeViewEvent() {
    //        let vc = MCPaymentCodeViewController()
    //        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    //    }
    
    @objc func deliveryViewEvent() {
        
        if MCUserinfo_getLevel() <= MCRole_salesStaff {
            MCHUD_text(message: "只有店长和店员才可编辑", view: self.view, delay: 1.2)
            return
        }
        
        let vc = MCStoreDeliveryViewController()
        vc.storeDict = self.storeDict
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    
    
    
    @objc func returnInfoViewEvent() {
        
        if MCUserinfo_getLevel() <= MCRole_salesStaff {
            MCHUD_text(message: "只有店长和店员才可编辑", view: self.view, delay: 1.2)
            return
        }
        
        let linkMan = refundAddress["linkMan"] as! String
        let mobile = refundAddress["mobile"] as! String
        let province = refundAddress["province"] as! String
        let city = refundAddress["city"] as! String
        let area = refundAddress["area"] as! String
        let address = refundAddress["address"] as! String
        
        
        let vc = MCReturnInfoViewController()
        vc.linkMan = linkMan
        vc.mobile = mobile
        vc.province = province
        vc.city = city
        vc.area = area
        vc.address = address
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
    
    @objc func storeBgImageViewEvent() {
        view.window?.addSubview(chooseImageView)
        chooseImageView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }
    
    
    @objc func changeStoreViewEvent() {
        let vc = MCChangeStoreViewController()
        MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
    }
}


//MARK: 网络请求
extension MCStoreDetailViewController {
    func sendNetworking() {
        
        let para = [
            "storeId" : MCUserinfo_getStoreId(),
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getStoreDetail, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as! [String : AnyObject]
            
            self.topView.dataDict = dataDict
            
            // 店铺信息
            self.storeDict = dataDict["store"] as! [String : Any]
            
            self.deliveryView.storeDict = self.storeDict
            
            // 退货信息
            self.refundAddress = dataDict["refundAddress"] as! [String : Any]
            
            // 分享店铺 第一张店铺图片
            let images = dataDict["images"] as? NSArray ?? []
            if images.count > 0 {
                let imageDict = images[0] as? [String:Any] ?? [:]
                self.firstStoreBgimage = imageDict["imgUrl"] as? String ?? ""
            }
            
        }, dislike: { (response) in }) { (error) in }
    }

    
    // 上传图片
    func sendNewworking_updateImage(_ image:UIImage) {
        let imageData = UIImageJPEGRepresentation(image, 0.1)
        let base = imageData?.base64EncodedString() ?? ""
        
        let para = [
            "catalog" : "2",
            "suffix"  : "png",
            "imgBase" : base
            ] as [String : Any]
        
        MCNetwork.POST(JAVA_imageBasePath, para, vc: self, success: { (data)
            in
            let imgUrl = data.stringValue
            self.sendNewworking_updateStoreBgImageUrl(imgUrl)
        })
    }
    
    // 上传店铺背景图url
    func sendNewworking_updateStoreBgImageUrl(_ url:String) {
        
        let para = [
            "images" : [url],
            ] as [String : Any]
        
        MCNetwork.POST(JAVA_saveStorePhoto, para, vc: self, success: { (data)
            in
            
            MCHUD_text(message: "上传店铺背景图成功", view: self.view, delay: 1.0)
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0, execute: {
                self.sendNetworking()
            })
        })
    }
}

//MARK: UI的处理,通知的接收
extension MCStoreDetailViewController {
    
    func baseSetting() {
        self.title = "店铺信息"
        self.view.backgroundColor = UIColor.white
        
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_image(#imageLiteral(resourceName: "Reuse_share_black"), target: self, selector: #selector(rightItemClicked))
    }
    
    func initUI() {
        view.addSubview(topView)
        topView.snp.remakeConstraints { (make) ->Void in
            make.left.right.top.equalTo(0)
            make.height.equalTo(MCScreenWidth/2 + 60)  // 提现功能打开，+ 50px
        }
        
        view.addSubview(deliveryView)
        deliveryView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.top.equalTo(topView.snp.bottom)
            make.height.equalTo(50)
        }
        
        
        view.addSubview(returnInfoView)
        returnInfoView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.top.equalTo(deliveryView.snp.bottom)
            make.height.equalTo(50)
        }
        
        view.addSubview(storeBgImageView)
        storeBgImageView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.top.equalTo(returnInfoView.snp.bottom)
            make.height.equalTo(50)
        }
        
        
        //        view.addSubview(paymentCodeView)
        //        paymentCodeView.snp.remakeConstraints { (make) ->Void in
        //            make.left.right.equalTo(0)
        //            make.top.equalTo(returnInfoView.snp.bottom)
        //            make.height.equalTo(50)
        //        }
        
        view.addSubview(changeStoreView)
        changeStoreView.snp.remakeConstraints { (make) ->Void in
            make.left.right.equalTo(0)
            make.top.equalTo(storeBgImageView.snp.bottom)
            make.height.equalTo(50)
        }
    }

}
